package com.thermofisher.dsc.amanda.auth.controller;

import com.thermofisher.dsc.amanda.auth.service.UserService;
import com.thermofisher.dsc.amanda.common.exception.BaseException;
import com.thermofisher.dsc.amanda.common.exception.ExceptionCode;
import com.thermofisher.dsc.amanda.common.tracking.TrackingAction;
import com.thermofisher.dsc.amanda.model.constant.ActionEnum;
import com.thermofisher.dsc.amanda.model.dto.auth.JwtLoginRequest;
import com.thermofisher.dsc.amanda.model.response.BaseResponse;
import com.thermofisher.dsc.amanda.model.response.DataResponse;

import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wenjie.yang on 12/29/2018.
 */
@Controller
public class AuthController {

  @Autowired
  private UserService userService;

  @PostMapping("/bio-login")
  @ResponseBody
  @TrackingAction(action = ActionEnum.CLICK_LOGIN)
  public BaseResponse login(@RequestBody JwtLoginRequest jwtLoginRequest) throws Exception {
    String jwtToken = userService.login(jwtLoginRequest);
    return new DataResponse(jwtToken);
  }

  @PostMapping("/auth-login")
  @ResponseBody
  public BaseResponse authLogin(@RequestBody Map<String, String> param) throws Exception {
    String token = param.get("token");
    String email = param.get("email");
    String timestamp = param.get("ts");
    String sourceMessage = email + "," + timestamp;
    if (StringUtils.isBlank(token) || !userService.isValidFromThridParty(sourceMessage, token)) {
      throw new BaseException(ExceptionCode.USER_TOKEN_FORBIDDEN_OR_EXPIRED, "token is wrong");
    }
    String jwtToken = userService.authLogin(email, Long.parseLong(timestamp));
    return new DataResponse(jwtToken);
  }


  @RequestMapping("/access")
  @ResponseBody
  public BaseResponse access() {
    return new BaseResponse(ExceptionCode.ACCESS_DENIED, "access denied");
  }
}
